<template>
  <a-modal v-model:open="ShowModalFlag" title="选择商品" @cancel="hideModal" @ok="hideModal" width="60vw" :bodyStyle="{ height: '520px' }">
    <template #default>
      <a-row :gutter="10">
        <a-col :span="4" style="margin-top: 10px">
          <CategoryTree ref="categoryTreeRef" v-model:value="company_cate_id" @update:value="() => queryData()" />
        </a-col>

        <a-col :span="20" style="background-color: #f8f8f8; padding: 20px; border-radius: 8px">
          <!---------- 查询表单form begin ----------->
          <a-form class="smart-query-form" :model="queryForm">
            <a-form-item label="商品名称" class="smart-margin-bottom0">
              <a-input v-model:value.trim="queryForm.goods_name" placeholder="商品名称" autofocus allow-clear />
            </a-form-item>
            <a-form-item label="商品编码" class="smart-margin-bottom0">
              <a-input v-model:value.trim="queryForm.no" placeholder="商品编码" allow-clear />
            </a-form-item>
            <a-button-group>
              <a-button type="primary" html-type="submit" @click="onSearch" v-privilege="'goods:query'">
                <template #icon>
                  <SearchOutlined />
                </template>
                查询
              </a-button>
              <a-button @click="resetQuery" v-privilege="'goods:query'">
                <template #icon>
                  <ReloadOutlined />
                </template>
                重置
              </a-button>
            </a-button-group>
          </a-form>

          <!---------- 查询表单form end ----------->
          <a-table size="small" :dataSource="tableData" :columns="columns" :loading="tableLoading" rowKey="id" bordered :scroll="{ x: 'auto', y: 320 }" :pagination="false" :showSorterTooltip="false" :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange, preserveSelectedRowKeys: true }">
            <template #bodyCell="{ text, record, column }">
              <template v-if="column.dataIndex === 'img'">
                <a-image :width="text ? 30 : 50" :src="text || failImg" />
              </template>
              <template v-if="column.dataIndex === 'barcode'">
                {{ _.find(record.spec, ['unit_type', record.default_unit_type])?.barcode }}
              </template>
              <template v-if="column.dataIndex === 'unit_name'">
                <a-radio-group v-model:value="record.default_unit_type" option-type="button" :options="_.map(record.spec, filterUnit)" />
              </template>
              <template v-if="column.dataIndex === 'spec_name'">
                {{ _.find(record.spec, ['unit_type', record.default_unit_type])?.spec_name }}
              </template>
              <template v-if="column.dataIndex === 'stock'">
                <span v-if="props.warehouseType === 2">
                  {{ getSpecQuantity(record['totalQuantities'], _.find(record.spec, ['unit_type', record.default_unit_type])) }}
                  {{ _.find(record.spec, ['unit_type', record.default_unit_type])?.unit_name }}
                </span>
                <span v-if="props.warehouseType === 1">
                  {{ getSpecQuantity(record['totalPreDeductedQuantities'], _.find(record.spec, ['unit_type', record.default_unit_type])) }}
                  {{ _.find(record.spec, ['unit_type', record.default_unit_type])?.unit_name }}
                </span>
              </template>
              <template v-if="column.dataIndex === 'sale_price'">
                {{ _.find(record.spec, ['unit_type', record.default_unit_type])?.sale_price }}
              </template>
            </template>
          </a-table>
          <div class="smart-query-table-page">
            <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="(total) => `共${total}条`" />
          </div>
        </a-col>
      </a-row>
    </template>
    <template #footer>
      <a-button type="primary" @click="onSubmit" html-type="button" style="margin-top: 10px">确定</a-button>
    </template>
  </a-modal>
</template>
<script setup lang="ts">
import _ from 'lodash'
import { message } from 'ant-design-vue'
import { useQuery } from '@/hooks/web/use-query-hook'
import { useTransformSpec } from '@/hooks/web/use-transform-spec'
import { PAGE_SIZE_OPTIONS } from '@/constants/system/common-const'
import { processOrderApi } from '@/api/business/storage/processing-api'
import { QUERY_FORM_OP } from '@/constants/support/query-form-op-const'
import CategoryTree from '@/components/business/category-tree/index.vue'
import failImg from '@/assets/images/notice/failImg.png'
const { getSpecQuantity } = useTransformSpec()
const emit = defineEmits(['confirm'])
const props = defineProps({
  checkStock: {
    type: Boolean,
    default: false // 是否检查库存
  },
  orderType: {
    type: Number,
    default: 1 // 1: 销售单 2: 退货单
  },
  warehouseType: {
    type: Number,
    default: 1 // 1: 固定 2: 移动
  },
  defaultSelectedKeys: {
    type: Array<number>,
    default: () => []
  }
})
// ---------------------------- 表格列 ----------------------------
const columns = computed(() => {
  const list = [
    {
      title: '图片',
      dataIndex: 'img'
    },
    {
      title: '商品名称',
      dataIndex: 'goods_name'
    },
    {
      title: '库存',
      dataIndex: 'stock',
      disabled: props.orderType === 2
    },
    {
      title: '单位',
      dataIndex: 'unit_name'
    },
    {
      title: '规格',
      dataIndex: 'spec_name',
      width: 100
    },
    {
      title: '单价',
      dataIndex: 'sale_price'
    },
    {
      title: '规格条码',
      dataIndex: 'barcode'
    },
    {
      title: '商品编码',
      dataIndex: 'no'
    }
  ]
  return list.filter((item) => !item.disabled)
})

// ---------------------------- 查询数据表单和方法 ----------------------------
const company_cate_id = ref(0)

const { queryForm, tableData, tableLoading, total, onSearch, resetQuery, queryData, setQuery } = useQuery({
  fetchDataApi: async (params) => {
    const result = {
      list: [],
      total: 0
    }
    const data = {
      ...params,
      cate_id: company_cate_id.value
    }
    const res = await processOrderApi.processList(data)
    result.list = res.data.data
    result.total = res.data.total

    return result
  },
  queryFormFilter: {
    dealer_id: undefined,
    goods_name: '',
    no: ''
  },
  queryFormOp: {
    dealer_id: QUERY_FORM_OP['全等查询'],
    goods_name: QUERY_FORM_OP['模糊查询'],
    no: QUERY_FORM_OP['模糊查询']
  }
})

// ---------------------------- 规格 ----------------------------
function filterUnit(specData) {
  return {
    label: specData.unit_name,
    value: specData.unit_type
  }
}

// 选择表格行
const selectedRowKeyList = ref<number[]>([])
const selectedRowList = ref<any[]>([])

function onSelectChange(selectedRowKeys: number[], selectedRows: any[]) {
  selectedRowKeyList.value = selectedRowKeys
  selectedRowList.value = selectedRows
}

const ShowModalFlag = ref(false)
function hideModal() {
  ShowModalFlag.value = false
  resetQuery()
  selectedRowList.value = []
  selectedRowKeyList.value = []
}
const warehouse_id = ref<number>()

function showModal(params: { warehouse_id: number; dealer_id: number }) {
  warehouse_id.value = params.warehouse_id
  setQuery({ dealer_id: params.dealer_id }, true)
  queryData()
  ShowModalFlag.value = true
}

function onSubmit() {
  try {
    if (props.checkStock) {
      selectedRowList.value.forEach((item) => {
        const stock = props.warehouseType === 2 ? item.totalQuantities : item.totalPreDeductedQuantities
        if (Number(getSpecQuantity(stock, _.find(item.spec, ['unit_type', item.default_unit_type]))) === 0) {
          // message.error(`${item.goods_name}库存不足！`)
          throw new Error(`${item.goods_name}库存不足！`)
        }
      })
    }
    if (selectedRowList.value.length > 0) {
      emit('confirm', selectedRowList.value)
      hideModal()
    }
  } catch (error) {
    message.error(error.message)
  }
}

defineExpose({
  showModal,
  hideModal
})
</script>

<style lang="less" scoped>
.smart-query-form {
  --grid-column-col: 4;
  padding-left: 0;
  padding-right: 0;
  background-color: #f8f8f8;
}
</style>
